package com.li.network.lab_1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class WebServer {
    public static String HOST = "http://localhost:8082";

    public static void main(String[] args) {
        int port = 6789;
        try (ServerSocket server = new ServerSocket(port)) {
            Socket socket = server.accept();
            System.out.println("===接收到请求===");
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while (!(line = br.readLine()).isEmpty()) {
                builder.append(line + "\n");
            }
            //解析请求
            HttpRequest request = HttpParser.parse(builder.toString());
            System.out.println(request);
            //根据url获取文件
            String resource = ResourceReader.read(request.getUrl());

            //构造响应报文
            HttpResponse httpResponse = new HttpResponse();
            if (resource == null) {
                httpResponse.setStatus(404);
            } else {
                byte[] body = resource.getBytes();
                httpResponse.setBody(body).setStatus(200);
            }
            System.out.println("===返回响应===");
            byte[] response = httpResponse.toBytes();
            System.out.println(new String(response));
            socket.getOutputStream().write(response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
